package com.sec.android.app.myfiles.operation;

import android.content.ContentResolver;
import android.content.Context;
import android.os.SystemClock;

import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.util.FileUtils;

import java.util.ArrayList;

public class FileOperationMediaDbThread extends Thread {
    private static final int BULK_CNT = 128;
    private int mOffset = BULK_CNT;
    private int mStart = 0;
    private boolean mRunning = true;
    private Context mContext;
    private ArrayList<Integer> mDeletedIdList;

    public FileOperationMediaDbThread(Context context) {
        mContext = context;
        mDeletedIdList = new ArrayList<>();
    }

    public void setRecordList(FileRecord recordList) {
        if (recordList.getId() >= 0) {
            mDeletedIdList.add(recordList.getId());
        }
    }

    public void clear() {
        mDeletedIdList.clear();
        mRunning = false;
    }

    public void run() {
        while (mRunning) {
            deleteMediaDb();
            SystemClock.sleep(100);
        }
    }

    private void deleteMediaDb() {
        if (mDeletedIdList.size() >= mOffset) {
            StringBuilder sb = null;
            ContentResolver resolver = mContext.getContentResolver();

            for (int i = mStart; i < mOffset; i++) {
                if (sb == null) {
                    sb = new StringBuilder();
                } else {
                    sb.append(',');
                }
                sb.append(mDeletedIdList.get(i));
            }

            if (sb != null) {
                long time = SystemClock.elapsedRealtime();
                int row = resolver.delete(FileUtils.MEDIA_PROVIDER_URI, "_id in ( " + sb.toString() + ")", null);
                time = SystemClock.elapsedRealtime() - time;
                Log.e(this, "delete media Db cnt" + row + " time = " + time);
            }

            sb = null;
            mStart = mOffset;
            mOffset = mOffset + BULK_CNT;
        }
    }
}